﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class IndexCheckStatsNotUpdated : IssueTypeCheckBase
    {

        public IndexCheckStatsNotUpdated()
        {
            IssueTypeId = 6004;
        }

        public override void Check()
        {
            try
            {
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;
                ThresholdValue thresholdValue = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);
                ThresholdValue thresholdValue2 = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 2);
                // Get all Service instance that has ServiceTypeID 1

                var QryIndex = from i in dc.Indexes

                               where (i.Statistics_LastUpdatedDate.Value < DateTime.Now.AddDays(Convert.ToDouble(thresholdValue.Value) * -1) && (i.IndexSize > thresholdValue2.Value)) 

                               select i;

                // Check number of Logins for each instance    
                foreach (var item in QryIndex)
                {

                    //Get Issuetype object

                    issue = new Issue();

                    //Get Issuetype object  And return first issue Id
                    IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                    issue.IssueType = issueType;
                    issue.TargetId = item.IndexID;


                    issue.Description = issueType.Description.Replace("{DatabaseName}", item.Table.Database.DatabaseName).Replace("{IndexName}", item.IndexName).Replace("{TableName}", item.Table.TableName).Replace("{IndexSize}", item.IndexSize.ToString()).Replace("{ThresholdValue1}",thresholdValue.Value.ToString());

                    dc.Issues.InsertOnSubmit(issue);


                }


                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }



        }



    }

}
